package scau.zxck.dao;

import scau.zxck.constant.ERROR;
import scau.zxck.exception.BaseException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by lsp on 27/11/2016.
 */
public class ConnDao {
    private static String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
    private static Connection conn;
    private String username;
    private String password;
    private String url;

    public ConnDao(String url, String username, String password) {
        this.username = username;
        this.password = password;
        this.url = url;
    }

    public Connection getConn() throws BaseException{
        try {
            Class.forName(MYSQL_DRIVER);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            throw new BaseException(ERROR.DB_CONN_ERROR, e);
        } catch (SQLException e) {
            throw new BaseException(ERROR.DB_CONN_ERROR, e);
        }
        return conn;
    }

    public void close() throws BaseException{
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new BaseException(ERROR.DB_CLOSE_ERROR, e);
            }
        }
    }
}
